package com.sportizz.sport;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import com.sportizz.model.player_search;

import android.content.Context;
import android.graphics.Typeface;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

public class PlacesAutoCompleteAdapter extends ArrayAdapter<player_search>
		implements Filterable {

	private ArrayList<String> resultList;
	private LayoutInflater mInflater = null;
	Context context;
 
	static public List<player_search> player_search;// = new
													// ArrayList<player_search>();
	 Typeface sport_font;
	 
	public PlacesAutoCompleteAdapter(Context context, int searchlistItem) {
		super(context, searchlistItem);
		this.context = context;
		player_search = new ArrayList<player_search>();
		sport_font = Typeface.createFromAsset(context.getAssets(),
					"hel57.ttf");
	}

	@Override
	public int getCount() {
		return player_search.size();
	}

	@Override
	public player_search getItem(int index) {
		return player_search.get(index);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    View rowView = inflater.inflate(R.layout.search_row, parent,
	            false);
	    TextView name= (TextView) rowView.findViewById(R.id.txt_searchname);
	    TextView sport = (TextView) rowView.findViewById(R.id.txt_searchsport);

	    name.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
	    sport.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
	    
	    String[] pl_data = resultList.get(position).split(":");
	    
	    name.setText(pl_data[0]);
	    sport.setText(pl_data[2]);
	    
	   name.setTypeface(sport_font);
	   sport.setTypeface(sport_font);
	   

	    return rowView;
	}

	@Override
	public Filter getFilter() {
		Filter filter = new Filter() {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults filterResults = new FilterResults();
				if (constraint != null) {

					MainActivity.result_main = new ArrayList<String>();

					resultList = autocomplete(constraint.toString().replace(
							" ", "%20"));

					filterResults.values = resultList;
					filterResults.count = resultList.size();

					MainActivity.result_main = resultList;

				}
				// MainActivity.result_main.clear();

				Log.d("suraj", " MainActivity.result_main Testinf = "
						+ MainActivity.result_main);

				return filterResults;
			}

			private ArrayList<String> autocomplete(String input) {
				
				ArrayList<String> result = null;

				HttpURLConnection conn = null;
				StringBuilder jsonResults = new StringBuilder();
				try {

					StringBuilder sb = new StringBuilder(
							"http://sportizza.com/interface/autocomplete.php?term="+input);

					URL url = new URL(sb.toString());
					conn = (HttpURLConnection) url.openConnection();
					InputStreamReader in = new InputStreamReader(
							conn.getInputStream());

					// Load the results into a StringBuilder
					int read;
					char[] buff = new char[1024];
					while ((read = in.read(buff)) != -1) {
						jsonResults.append(buff, 0, read);
					}
				} catch (MalformedURLException e) {
					Log.e("suraj", "Error processing Places API URL", e);
					return result;
				} catch (IOException e) {
					Log.e("suraj", "Error connecting to Places API", e);
					return result;
				} finally {
					if (conn != null) {
						conn.disconnect();
					}
				}

				try {
					JSONArray predsJsonArray = new JSONArray(
							jsonResults.toString());// .getJSONArray("predictions");
					result = new ArrayList<String>(predsJsonArray.length());

					 player_search.clear();

					for (int i = 0; i < predsJsonArray.length(); i++) {

						// MainActivity.result_main.add(predsJsonArray
						// .getJSONObject(i).getString("ss_player_name")
						// + ":"
						// + predsJsonArray.getJSONObject(i).getString(
						// "ss_player_code")
						// + ":"
						// + predsJsonArray.getJSONObject(i).getString(
						// "ss_sport")
						// + ":"
						// + predsJsonArray.getJSONObject(i).getString(
						// "ss_is_team"));

						player_search.add(new player_search(predsJsonArray
								.getJSONObject(i).getString("ss_player_name"),
								predsJsonArray.getJSONObject(i).getString(
										"ss_player_code"),
								predsJsonArray.getJSONObject(i).getString(
										"ss_sport"), predsJsonArray
										.getJSONObject(i).getString(
												"ss_is_team")));

						result.add(predsJsonArray.getJSONObject(i).getString(
								"ss_player_name")
								+ ":"
								+ predsJsonArray.getJSONObject(i).getString(
										"ss_player_code")
								+ ":"
								+ predsJsonArray.getJSONObject(i).getString(
										"ss_sport")
								+ ":"
								+ predsJsonArray.getJSONObject(i).getString(
										"ss_is_team"));

					}
					// Log.w("suraj","result Json ="+result);

					// MainActivity.result_main = result;
				} catch (JSONException e) {
					Log.e("suraj", "Cannot process JSON results", e);
				}

				return result;
			}

			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				if (results != null && results.count > 0) {
					notifyDataSetChanged();
				} else {
					notifyDataSetInvalidated();
				}
			}
		};
		return filter;
	}
}